class ArtistLinksController < ApplicationController
  #filter_access_to :all
  before_filter :find_item
  
  #If AJAX request, use the slim layout (no header or footer)
  #Otherwise use the main layout
  layout Proc.new { |controller| controller.request.xhr? ? 'slim' : 'main' }
  

  #
  def new

  end
  
   ##
  def search
    #@artist = Artist.find(params[:artist_id])
    @artist_search = Artist.search(params[:search])

    if !params[:search].nil?  && !params[:search][:name_like].blank?
      @artists = @artist_search.all
    end
	
  	respond_to do |format|
	  format.js {
	    render :update do |page|
		  page.replace_html("artist-links-search-results", :partial => "results",
		                            :locals => {:artists => @artists, :item => @item})
		end
	  }
	end
  
  end
  
  #
  def create
    #Either creates a new artist, or find the selected one
    if params[:name] != nil && params[:artist_id].nil?
      artist = Artist.new(:name => params[:name])
      artist.save
    elsif params[:artist_id]
      artist = Artist.find(params[:artist_id])
    end

    # Link the artist
    if !@item.artists.exists?(artist) && @item.artists << artist
      flash[:notice] = 'Artist successfully added.'

      #Create edit
      entry = Hash.new
      entry.store("linked artist", [artist.name])
      Edit.create_edit(entry, @item)

      redirect_to_request_uri
    else
      flash[:errors] = 'Unable to add artist to entry, please try again.'
      redirect_to_request_uri
    end
  end

  def remove
    artist = Artist.find(params[:artist_id])
	
	#
	respond_to do |format|
	  if @item.artists.delete(artist)
	    flash[:notice] = 'Artist successfully removed from this entry.'
		#Create edit
        entry = Hash.new
        entry.store("unlinked artist", [artist.name])
        Edit.create_edit(entry, @item)
		
	    format.html { redirect_to_request_uri }
		format.js {
		  render :update do |page|
		    page.remove(@container_name)
		  end
		}
	  else
	    format.html { redirect_to_request_uri }
		format.js {
		  render :update do |page|
		    page.replace_html(:errors, @item.errors.full_messages)
		  end
		}
	  end
	end
  end

  private

  #Returns the item to be worked on based on whether
  # the request came from a song or release record
  def find_item
    if params[:release_id]
      @item = Release.find(params[:release_id])
	  @search_url = search_release_artist_links_path
	  @container_name = "release-artist-" + params[:artist_id].to_s
    elsif params[:song_id]
      @item = Song.find(params[:song_id])
	  @search_url = search_song_artist_links_path
	  @container_name = "song-artist-" + params[:artist_id].to_s
    end
  end

end
